<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model.trim="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="onSearch"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="elTreeRef"
          default-expand-all
          :data="depts"
          :props="defaultProps"
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true" @uploadSuccess="getDepartment">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="selectNode"
        >
          <el-table-column type="selection" width="30px" />
          <el-table-column label="头像" align="center">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" align="center" />
          <el-table-column prop="mobile" label="手机号" align="center" width="120px" sortable />
          <el-table-column prop="workNumber" label="工号" align="center" width="120px" sortable />
          <el-table-column prop="address" label="聘用形式" align="center">
            <template #default="{ row }">
              {{ row.formOfEmployment === 1 ? '正式' : '非正式' }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" align="center" />
          <el-table-column prop="timeOfEntry" label="入职时间" width="100px" sortable />
          <el-table-column prop="address" label="操作" align="center" width="120px">
            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确定要删除该用户吗？" style="margin-left:10px" @onConfirm="delEmploy(row.id)">
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
      <!-- 上传文件弹层 -->
      <ImportExcel :show-excel-dialog.sync="showExcelDialog" />

      <!-- 分配角色弹窗 -->
      <el-dialog :visible.sync="showRoleDialog" title="分配角色" append-to-body>
        <!-- 弹层内容 -->
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">
            {{ role.name }}
          </el-checkbox>
          <el-row style="text-align:center;margin-top:20px">
            <el-button size="mini" type="primary" @click="onOnConfirm">确认</el-button>
            <el-button size="mini" @click="onCancel">取消</el-button>
          </el-row>
        </el-checkbox-group>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getDepartmentApi } from '@/api/department'
import { delEmployApi, exportEmployeeApi, getEmployeeDetailApi, getEmployListApi } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
import { assignRoleApi, getEnableRoleListApi } from '@/api/role'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 数据组件数据数组
      defaultProps: { // 默认属性
        label: 'name',
        children: 'children'
      },
      tableData: [],
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 8,
        keyword: ''
      },
      total: 0,
      showExcelDialog: false, // 控制上传弹层的显示/隐藏
      // --------------分配角色相关---------------
      roleList: [], // 接收角色列表
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleIds: [], // 该用户拥有的角色
      currentId: '' // 当前用户的id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartmentApi()
      this.depts = transListToTreeData(res, 0) // 把对象数组转成树形数组
      // 设置当前选中的节点的key值
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(async() => {
        this.$refs.elTreeRef.setCurrentKey(this.queryParams.departmentId)
        this.getEmployeeList()
      })
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployListApi(this.queryParams)
      this.tableData = rows
      this.total = total
    },
    async selectNode(node) {
      this.queryParams.departmentId = node.id
      this.getEmployeeList()
    },
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList() // 查询数据
    },
    onSearch() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getEmployeeList()
      }, 300)
    },
    async exportEmployee() {
      const blob = await exportEmployeeApi()
      FileSaver.saveAs(blob, '员工信息表.xlsx')
    },
    async delEmploy(id) {
      try {
        await delEmployApi(id)
        if (this.tableData.length === 1 && this.queryParams.page > 1) {
          this.queryParams.page--
        }
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        setTimeout(() => {
          this.$message.error('删除员工失败')
        }, 500)
      }
    },
    // 打开分配角色弹窗
    async btnRole(id) {
      this.currentId = id
      this.roleList = await getEnableRoleListApi()

      // 2. 获取当前用户拥有的id数组
      const { roleIds } = await getEmployeeDetailApi(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async onOnConfirm() {
      await assignRoleApi({
        id: this.currentId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.onCancel()
    },
    onCancel() {
      this.roleIds = []
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
